package com.bang.middle.server.rabbitmq.publisher;

import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Strings;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @author qinxubang
 * @Date 2021/4/23 15:30
 */
@Component
@Slf4j
public class BasicPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    Environment env;

    // 发送字符串类型的消息
    public void sendMsg(String messageStr) {
        if (!Strings.isNullOrEmpty(messageStr)) {
            try {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                rabbitTemplate.setExchange(env.getProperty("mq.basic.info.exchange.name"));
                rabbitTemplate.setRoutingKey(env.getProperty("mq.basic.info.routing.key.name"));

                // 2创建队列、交换机、消息 设置持久化模式
                // 设置消息的持久化模式
                Message message = MessageBuilder.withBody(messageStr.getBytes("utf-8")).
                        setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
                rabbitTemplate.convertAndSend(message);
                log.info("基本消息模型-生产者-发送消息：{}", messageStr);

            } catch (UnsupportedEncodingException e) {
                log.error("基本消息模型-生产者-发送消息发生异常：{}", messageStr, e.fillInStackTrace());
            }
        }
    }

}
